package com.guxingke.typecho4j.widget.handle.content;

import java.io.File;
import java.util.List;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.jfinal.model.User;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.util.DateUtil;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;

/**
 * 新增评论处理组件
 * 
 * @author guxingke
 * */
public class FileUploadHandleWidget extends ContentBaseWidget implements
		WidgetHandle {

	@Override
	public void handle(Controller controller) throws Typecho4jException {

		List<UploadFile> files = controller.getFiles(PathKit
				.getWebRootPath()
				+ File.separator
				+ constants.getUploadPath());

		String title = null;
		for (UploadFile file : files) {
			title = file.getFileName();
			// TODO 暂时没考虑不是图片的情况
			controller.setAttr("isImage", true);
			controller.setAttr("bytes", file.getFile()
					.getAbsolutePath().getBytes().length);
		}

		Content content = new Content();
		content.set("authorId", (((User) controller
				.getSessionAttr("user")).get("cid")));
		content.set("title", title);
		content.set("status", "publish");
		content.set("type", "attachment");
		content.set("created", DateUtil.getUnixTimestamp());
		content.set("modified", DateUtil.getUnixTimestamp());
		content.save();

		controller.setAttr("cid", content.get("cid"));
		controller.setAttr("title", title);
		controller.setAttr("url", constants.getSiteUrl()
				+ File.separator + constants.getUploadPath()
				+ File.separator + title);

		controller.renderJson();
	}

	@Override
	public void configRoute(Routes routes) {
		routes.addRoute(new Route("upload", this.getClass(), null));
	}
}
